<template>
  <div class="rpg-container">
    <div class="game-header">
      <div class="player-stats">
        <div class="stat">
          <span class="label">生命值</span>
          <span class="value">{{ player.hp }}/{{ player.maxHp }}</span>
        </div>
        <div class="stat">
          <span class="label">等级</span>
          <span class="value">{{ player.level }}</span>
        </div>
        <div class="stat">
          <span class="label">经验值</span>
          <span class="value">{{ player.exp }}/{{ player.nextLevelExp }}</span>
        </div>
      </div>
      <div class="controls">
        <button class="control-btn" @click="$router.push('/')">返回</button>
      </div>
    </div>

    <div class="game-world">
      <canvas ref="gameCanvas" :width="800" :height="600"></canvas>
    </div>

    <div class="mobile-controls" v-if="isMobile">
      <div class="direction-pad">
        <button @click="move('up')">↑</button>
        <button @click="move('left')">←</button>
        <button @click="move('right')">→</button>
        <button @click="move('down')">↓</button>
      </div>
      <button class="action-btn" @click="action">行动</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const gameCanvas = ref(null)
const isMobile = ref(false)

// 首先定义游戏配置
const GAME_CONFIG = {
  ENEMY_SPAWN_INTERVAL: 2000,  // 敌人生成间隔(毫秒)
  SHOOT_COOLDOWN: 500,        // 射击冷却时间(毫秒)
  EXP_PER_ORB: 20,           // 每个经验球经验值
  BULLET_SPEED: 8,           // 子弹速度
  ENEMY_SPEED: 0.8,          // 敌人速度
  EXP_ORB_COLLECT_DISTANCE: 50, // 经验球收集距离
  ENEMY_DAMAGE: 10,          // 敌人伤害值
  DAMAGE_COOLDOWN: 1000,     // 受伤冷却时间(毫秒)
  ENEMY_BASE_HP: 50,         // 敌人基础血量
  ENEMY_HP_GROWTH: 10,       // 每级敌人血量增长
  WORLD_WIDTH: 2400,         // 游戏世界宽度
  WORLD_HEIGHT: 1800,        // 游戏世界高度
  VIEWPORT_WIDTH: 800,       // 视口宽度
  VIEWPORT_HEIGHT: 600,      // 视口高度
  MAGAZINE_SIZE: 8,          // 弹夹容量
  RELOAD_TIME: 1500          // 换弹时间(毫秒)
}

// 添加游戏实体
const enemies = ref([])
const bullets = ref([])
const expOrbs = ref([])

// 然后定义玩家属性
const player = ref({
  x: GAME_CONFIG.WORLD_WIDTH / 2,
  y: GAME_CONFIG.WORLD_HEIGHT / 2,
  speed: 4,
  hp: 100,
  maxHp: 100,
  level: 1,
  exp: 0,
  nextLevelExp: 100,
  damage: 20,
  shootCooldown: 0,
  damageCooldown: 0,
  ammoInMag: GAME_CONFIG.MAGAZINE_SIZE,  // 当前弹夹中的子弹数
  isReloading: false,                    // 是否正在换弹
  reloadTimeLeft: 0                      // 剩余换弹时间
})

// 添加摄像机位置
const camera = ref({
  x: 0,
  y: 0
})

// 游戏状态
let ctx
let gameLoop
let lastTime = 0

// 添加键盘状态追踪
const keys = ref({
  up: false,
  down: false,
  left: false,
  right: false
})

// 初始化游戏
const init = () => {
  ctx = gameCanvas.value.getContext('2d')
  isMobile.value = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  
  // 设置初始摄像机位置
  camera.value.x = player.value.x - GAME_CONFIG.VIEWPORT_WIDTH / 2
  camera.value.y = player.value.y - GAME_CONFIG.VIEWPORT_HEIGHT / 2
  
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyPress)
  window.addEventListener('keyup', handleKeyUp)
  
  // 开始游戏循环
  gameLoop = requestAnimationFrame(update)
}

// 游戏主循环
const update = (timestamp) => {
  const deltaTime = timestamp - lastTime
  lastTime = timestamp
  
  // 更新换弹计时器
  if (player.value.isReloading) {
    player.value.reloadTimeLeft -= deltaTime
    if (player.value.reloadTimeLeft <= 0) {
      // 换弹完成
      player.value.isReloading = false
      player.value.ammoInMag = GAME_CONFIG.MAGAZINE_SIZE
    }
  }
  
  // 更新受伤冷却
  if (player.value.damageCooldown > 0) {
    player.value.damageCooldown -= deltaTime
  }
  
  // 处理持续移动
  if (keys.value.up) player.value.y -= player.value.speed
  if (keys.value.down) player.value.y += player.value.speed
  if (keys.value.left) player.value.x -= player.value.speed
  if (keys.value.right) player.value.x += player.value.speed
  
  // 限制玩家在世界范围内
  player.value.x = Math.max(20, Math.min(GAME_CONFIG.WORLD_WIDTH - 20, player.value.x))
  player.value.y = Math.max(20, Math.min(GAME_CONFIG.WORLD_HEIGHT - 20, player.value.y))
  
  // 更新摄像机位置，使玩家保持在屏幕中心
  camera.value.x = player.value.x - GAME_CONFIG.VIEWPORT_WIDTH / 2
  camera.value.y = player.value.y - GAME_CONFIG.VIEWPORT_HEIGHT / 2
  
  // 限制摄像机不超出世界边界
  camera.value.x = Math.max(0, Math.min(GAME_CONFIG.WORLD_WIDTH - GAME_CONFIG.VIEWPORT_WIDTH, camera.value.x))
  camera.value.y = Math.max(0, Math.min(GAME_CONFIG.WORLD_HEIGHT - GAME_CONFIG.VIEWPORT_HEIGHT, camera.value.y))
  
  // 更新射击冷却
  if (player.value.shootCooldown > 0) {
    player.value.shootCooldown -= deltaTime
  }
  
  // 自动寻找最近的敌人并射击
  if (player.value.shootCooldown <= 0 && enemies.value.length > 0) {
    const nearestEnemy = findNearestEnemy()
    if (nearestEnemy) {
      shoot(nearestEnemy)
      player.value.shootCooldown = GAME_CONFIG.SHOOT_COOLDOWN
    }
  }
  
  // 更新子弹位置和碰撞检测
  updateBullets()
  
  // 更新敌人位置
  updateEnemies()
  
  // 更新经验球收集
  updateExpOrbs()
  
  // 绘制游戏画面
  draw()
  
  gameLoop = requestAnimationFrame(update)
}

// 寻找最近的敌人
const findNearestEnemy = () => {
  let nearest = null
  let minDistance = Infinity
  
  // 计算视口范围
  const viewportLeft = camera.value.x
  const viewportRight = camera.value.x + GAME_CONFIG.VIEWPORT_WIDTH
  const viewportTop = camera.value.y
  const viewportBottom = camera.value.y + GAME_CONFIG.VIEWPORT_HEIGHT
  
  // 扩展检测范围（比视口大一些）
  const extendedRange = 200
  
  enemies.value.forEach(enemy => {
    // 检查敌人是否在扩展的视口范围内
    if (enemy.x >= viewportLeft - extendedRange && 
        enemy.x <= viewportRight + extendedRange && 
        enemy.y >= viewportTop - extendedRange && 
        enemy.y <= viewportBottom + extendedRange) {
      
      const distance = getDistance(player.value, enemy)
      if (distance < minDistance) {
        minDistance = distance
        nearest = enemy
      }
    }
  })
  
  return nearest
}

// 射击
const shoot = (target) => {
  // 如果正在换弹或弹夹为空，则不能射击
  if (player.value.isReloading || player.value.ammoInMag <= 0) {
    // 如果弹夹为空且没有在换弹，则自动开始换弹
    if (player.value.ammoInMag <= 0 && !player.value.isReloading) {
      startReload()
    }
    return
  }

  const angle = Math.atan2(
    target.y - player.value.y,
    target.x - player.value.x
  )
  
  bullets.value.push({
    x: player.value.x,
    y: player.value.y,
    dx: Math.cos(angle) * GAME_CONFIG.BULLET_SPEED,
    dy: Math.sin(angle) * GAME_CONFIG.BULLET_SPEED,
    damage: player.value.damage
  })

  // 减少弹夹中的子弹
  player.value.ammoInMag--
}

// 添加换弹函数
const startReload = () => {
  if (!player.value.isReloading && player.value.ammoInMag < GAME_CONFIG.MAGAZINE_SIZE) {
    player.value.isReloading = true
    player.value.reloadTimeLeft = GAME_CONFIG.RELOAD_TIME
  }
}

// 更新子弹
const updateBullets = () => {
  bullets.value.forEach((bullet, bulletIndex) => {
    // 更新子弹位置
    bullet.x += bullet.dx
    bullet.y += bullet.dy
    
    // 检查子弹是否击中敌人
    enemies.value.forEach((enemy, enemyIndex) => {
      if (getDistance(bullet, enemy) < 20) {
        // 减少敌人血量
        enemy.hp -= bullet.damage
        
        // 如果敌人死亡
        if (enemy.hp <= 0) {
          // 生成经验球
          expOrbs.value.push({
            x: enemy.x,
            y: enemy.y
          })
          
          // 移除敌人
          enemies.value.splice(enemyIndex, 1)
        }
        
        // 移除子弹
        bullets.value.splice(bulletIndex, 1)
      }
    })
    
    // 移除超出世界范围的子弹
    if (bullet.x < 0 || 
        bullet.x > GAME_CONFIG.WORLD_WIDTH || 
        bullet.y < 0 || 
        bullet.y > GAME_CONFIG.WORLD_HEIGHT) {
      bullets.value.splice(bulletIndex, 1)
    }
  })
}

// 更新敌人
const updateEnemies = () => {
  if (Math.random() < 0.02) {
    const side = Math.floor(Math.random() * 4)
    let x, y
    
    // 在视口外生成敌人
    const margin = 50
    switch(side) {
      case 0: // 上
        x = camera.value.x + Math.random() * GAME_CONFIG.VIEWPORT_WIDTH
        y = camera.value.y - margin
        break
      case 1: // 下
        x = camera.value.x + Math.random() * GAME_CONFIG.VIEWPORT_WIDTH
        y = camera.value.y + GAME_CONFIG.VIEWPORT_HEIGHT + margin
        break
      case 2: // 左
        x = camera.value.x - margin
        y = camera.value.y + Math.random() * GAME_CONFIG.VIEWPORT_HEIGHT
        break
      case 3: // 右
        x = camera.value.x + GAME_CONFIG.VIEWPORT_WIDTH + margin
        y = camera.value.y + Math.random() * GAME_CONFIG.VIEWPORT_HEIGHT
        break
    }
    
    // 确保敌人在世界范围内
    x = Math.max(0, Math.min(GAME_CONFIG.WORLD_WIDTH, x))
    y = Math.max(0, Math.min(GAME_CONFIG.WORLD_HEIGHT, y))
    
    enemies.value.push({
      x,
      y,
      color: `hsl(${Math.random() * 360}, 70%, 50%)`,
      hp: GAME_CONFIG.ENEMY_BASE_HP + GAME_CONFIG.ENEMY_HP_GROWTH * (player.value.level - 1),
      maxHp: GAME_CONFIG.ENEMY_BASE_HP + GAME_CONFIG.ENEMY_HP_GROWTH * (player.value.level - 1)
    })
  }
  
  // 更新敌人位置和检查碰撞
  enemies.value.forEach(enemy => {
    const angle = Math.atan2(
      player.value.y - enemy.y,
      player.value.x - enemy.x
    )
    enemy.x += Math.cos(angle) * GAME_CONFIG.ENEMY_SPEED
    enemy.y += Math.sin(angle) * GAME_CONFIG.ENEMY_SPEED
    
    // 检查与玩家的碰撞
    if (getDistance(player.value, enemy) < 35 && player.value.damageCooldown <= 0) { // 35是碰撞半径(玩家20 + 敌人15)
      // 扣除生命值
      player.value.hp -= GAME_CONFIG.ENEMY_DAMAGE
      
      // 设置受伤冷却
      player.value.damageCooldown = GAME_CONFIG.DAMAGE_COOLDOWN
      
      // 检查是否死亡
      if (player.value.hp <= 0) {
        gameOver()
      }
    }
  })
}

// 更新经验球
const updateExpOrbs = () => {
  expOrbs.value.forEach((orb, index) => {
    // 检查是否被收集
    if (getDistance(player.value, orb) < GAME_CONFIG.EXP_ORB_COLLECT_DISTANCE) {
      // 增加经验值
      player.value.exp += GAME_CONFIG.EXP_PER_ORB
      
      // 检查是否升级
      if (player.value.exp >= player.value.nextLevelExp) {
        levelUp()
      }
      
      // 移除经验球
      expOrbs.value.splice(index, 1)
    }
  })
}

// 升级
const levelUp = () => {
  player.value.level++
  player.value.exp = 0
  player.value.nextLevelExp = Math.floor(player.value.nextLevelExp * 1.2)
  player.value.damage += 5
  player.value.maxHp += 20
  player.value.hp = player.value.maxHp
}

// 计算两点之间距离
const getDistance = (point1, point2) => {
  return Math.sqrt(
    Math.pow(point2.x - point1.x, 2) + 
    Math.pow(point2.y - point1.y, 2)
  )
}

// 修改绘制函数
const draw = () => {
  // 清空画布
  ctx.clearRect(0, 0, gameCanvas.value.width, gameCanvas.value.height)
  
  // 绘制背景网格
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)'
  ctx.lineWidth = 1
  const gridSize = 50
  const startX = Math.floor(camera.value.x / gridSize) * gridSize
  const startY = Math.floor(camera.value.y / gridSize) * gridSize
  
  for (let x = startX; x < startX + GAME_CONFIG.VIEWPORT_WIDTH + gridSize; x += gridSize) {
    const screenX = x - camera.value.x
    ctx.beginPath()
    ctx.moveTo(screenX, 0)
    ctx.lineTo(screenX, GAME_CONFIG.VIEWPORT_HEIGHT)
    ctx.stroke()
  }
  
  for (let y = startY; y < startY + GAME_CONFIG.VIEWPORT_HEIGHT + gridSize; y += gridSize) {
    const screenY = y - camera.value.y
    ctx.beginPath()
    ctx.moveTo(0, screenY)
    ctx.lineTo(GAME_CONFIG.VIEWPORT_WIDTH, screenY)
    ctx.stroke()
  }
  
  // 绘制玩家
  const playerScreen = worldToScreen(player.value.x, player.value.y)
  if (player.value.damageCooldown > 0 && Math.floor(player.value.damageCooldown / 100) % 2) {
    ctx.globalAlpha = 0.5
  }
  
  ctx.fillStyle = '#ff5f16'
  ctx.beginPath()
  ctx.arc(playerScreen.x, playerScreen.y, 20, 0, Math.PI * 2)
  ctx.fill()
  
  ctx.globalAlpha = 1
  
  // 绘制玩家血条
  const healthBarWidth = 40
  const healthBarHeight = 4
  const healthPercentage = player.value.hp / player.value.maxHp
  
  ctx.fillStyle = 'rgba(255, 0, 0, 0.3)'
  ctx.fillRect(
    playerScreen.x - healthBarWidth/2,
    playerScreen.y - 30,
    healthBarWidth,
    healthBarHeight
  )
  
  ctx.fillStyle = '#f00'
  ctx.fillRect(
    playerScreen.x - healthBarWidth/2,
    playerScreen.y - 30,
    healthBarWidth * healthPercentage,
    healthBarHeight
  )
  
  // 绘制敌人
  enemies.value.forEach(enemy => {
    const enemyScreen = worldToScreen(enemy.x, enemy.y)
    
    ctx.fillStyle = enemy.color
    ctx.beginPath()
    ctx.arc(enemyScreen.x, enemyScreen.y, 15, 0, Math.PI * 2)
    ctx.fill()
    
    // 绘制敌人血条
    const healthBarWidth = 30
    const healthBarHeight = 3
    const healthPercentage = enemy.hp / enemy.maxHp
    
    ctx.fillStyle = 'rgba(255, 0, 0, 0.3)'
    ctx.fillRect(
      enemyScreen.x - healthBarWidth/2,
      enemyScreen.y - 25,
      healthBarWidth,
      healthBarHeight
    )
    
    ctx.fillStyle = '#f00'
    ctx.fillRect(
      enemyScreen.x - healthBarWidth/2,
      enemyScreen.y - 25,
      healthBarWidth * healthPercentage,
      healthBarHeight
    )
  })
  
  // 绘制子弹
  bullets.value.forEach(bullet => {
    const bulletScreen = worldToScreen(bullet.x, bullet.y)
    
    // 计算子弹的角度
    const angle = Math.atan2(bullet.dy, bullet.dx)
    
    // 保存当前画布状态
    ctx.save()
    
    // 移动到子弹位置并旋转
    ctx.translate(bulletScreen.x, bulletScreen.y)
    ctx.rotate(angle)
    
    // 绘制子弹主体
    ctx.fillStyle = '#fff'
    ctx.beginPath()
    ctx.moveTo(-8, -2)  // 子弹尾部
    ctx.lineTo(8, 0)    // 子弹头部
    ctx.lineTo(-8, 2)   // 子弹尾部
    ctx.closePath()
    ctx.fill()
    
    // 添加发光效果
    ctx.shadowColor = '#ff5f16'
    ctx.shadowBlur = 5
    
    // 恢复画布状态
    ctx.restore()
  })
  
  // 绘制经验球
  ctx.fillStyle = '#4f4'
  expOrbs.value.forEach(orb => {
    const orbScreen = worldToScreen(orb.x, orb.y)
    ctx.beginPath()
    ctx.arc(orbScreen.x, orbScreen.y, 8, 0, Math.PI * 2)
    ctx.fill()
  })

  // 在玩家血条上方显示弹药信息
  ctx.fillStyle = '#fff'
  ctx.font = '12px Arial'
  ctx.textAlign = 'center'
  
  if (player.value.isReloading) {
    ctx.fillText('换弹中...', playerScreen.x, playerScreen.y - 35)
  } else {
    ctx.fillText(`${player.value.ammoInMag}/${GAME_CONFIG.MAGAZINE_SIZE}`, playerScreen.x, playerScreen.y - 35)
  }
}

// 世界坐标转屏幕坐标
const worldToScreen = (worldX, worldY) => {
  return {
    x: worldX - camera.value.x,
    y: worldY - camera.value.y
  }
}

// 移动控制
const move = (direction) => {
  switch(direction) {
    case 'up':
      player.value.y -= player.value.speed
      break
    case 'down':
      player.value.y += player.value.speed
      break
    case 'left':
      player.value.x -= player.value.speed
      break
    case 'right':
      player.value.x += player.value.speed
      break
  }
}

// 修改键盘控制函数
const handleKeyPress = (event) => {
  if (event.repeat) return // 防止按键重复触发
  
  // 阻止方向键的默认行为
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(event.key)) {
    event.preventDefault()
  }
  
  switch(event.key) {
    case 'ArrowUp':
      keys.value.up = true
      break
    case 'ArrowDown':
      keys.value.down = true
      break
    case 'ArrowLeft':
      keys.value.left = true
      break
    case 'ArrowRight':
      keys.value.right = true
      break
    case ' ':
      action()
      break
    case 'r':
    case 'R':
      startReload()
      break
  }
}

// 修改键盘释放事件处理
const handleKeyUp = (event) => {
  // 同样阻止方向键的默认行为
  if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(event.key)) {
    event.preventDefault()
  }
  
  switch(event.key) {
    case 'ArrowUp':
      keys.value.up = false
      break
    case 'ArrowDown':
      keys.value.down = false
      break
    case 'ArrowLeft':
      keys.value.left = false
      break
    case 'ArrowRight':
      keys.value.right = false
      break
  }
}

// 行动按钮
const action = () => {
  // 待实现交互逻辑
  console.log('执行动作')
}

// 添加游戏结束函数
const gameOver = () => {
  isPlaying.value = false
  cancelAnimationFrame(gameLoop)
  alert(`游戏结束！\n等级: ${player.value.level}`)
  resetGame()
}

onMounted(() => {
  init()
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyPress)
  window.removeEventListener('keyup', handleKeyUp)
  cancelAnimationFrame(gameLoop)
})
</script>

<style scoped>
.rpg-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 100%);
  min-height: 100vh;
  color: #fff;
}

.game-header {
  width: 100%;
  max-width: 800px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 1rem;
  margin-bottom: 2rem;
}

.player-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 1rem;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.label {
  font-size: 0.9em;
  color: rgba(255, 255, 255, 0.6);
}

.value {
  font-size: 1.2em;
  color: #ff5f16;
  font-weight: bold;
}

.game-world {
  background: rgba(255, 255, 255, 0.05);
  padding: 1rem;
  border-radius: 15px;
}

canvas {
  border: 2px solid rgba(255, 95, 22, 0.3);
  border-radius: 10px;
  background: #000;
}

.mobile-controls {
  margin-top: 2rem;
  display: flex;
  gap: 2rem;
}

.direction-pad {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.5rem;
}

.direction-pad button {
  padding: 1.2rem;
  border: none;
  border-radius: 10px;
  background: rgba(255, 95, 22, 0.8);
  color: white;
  font-size: 1.4em;
}

.direction-pad button:nth-child(1) { grid-column: 2; }
.direction-pad button:nth-child(2) { grid-column: 1; grid-row: 2; }
.direction-pad button:nth-child(3) { grid-column: 3; grid-row: 2; }
.direction-pad button:nth-child(4) { grid-column: 2; grid-row: 3; }

.action-btn {
  padding: 1.2rem 2rem;
  border: none;
  border-radius: 10px;
  background: #ff5f16;
  color: white;
  font-weight: bold;
}

button:active {
  transform: scale(0.95);
}

@media (max-width: 768px) {
  .game-world canvas {
    width: 100%;
    height: auto;
  }
}
</style>